﻿using ESXPowerTools.Controller.Exceptions;
using ESXPowerTools.Controller.Objects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VIX;
using VIX.Enums;

namespace ESXPowerTools.Controller
{
    /// <summary>
    /// Main Class , Keeps Everything In 1 Place.
    /// </summary>
    public class ESXPowerTools
    {
        #region BackFields

        /// <summary>
        /// BK Field for VixHost
        /// </summary>
        private Host vixHost;

        #endregion

        #region Properties

        /// <summary>
        /// Keeps Host Object - Connection to Esx.
        /// </summary>
        private Host VixHost 
        {
            get
            {
                if (vixHost == null)
                    throw new ESXPowerToolsException("You Must Open Connection");
                return vixHost;
            }
            set
            { 
                vixHost = value; 
            }
        }

        #endregion

        #region C'TOR

        /// <summary>
        /// C'TOR - Empty 4 Now.
        /// </summary>
        public ESXPowerTools()
        {
        }

        #endregion

        #region Public Methods
        
        /// <summary>
        /// Init New EsxConnection
        /// </summary>
        /// <param name="sdkUrl">Esx Sdk Url-Https://10.0.0.1/sdk</param>
        /// <param name="username">username</param>
        /// <param name="password">pass</param>
        /// <exception cref="ESXPowerToolsException">Any Login Error</exception>
        public void OpenConnection(string sdkUrl,string username , string password)
        {
            try
            {
                this.VixHost = VIX.VixCOMWrapper.Instance.Connect(VIX_SERVICEPROVIDER.VMWARE_VI_SERVER, sdkUrl, 0, username, password);
            }
            catch (Exception ex)
            {
                throw new ESXPowerToolsException("Login Error", ex);
            }
        }

        /// <summary>
        /// This Method Returns VM List.
        /// </summary>
        /// <param name="runningOnly">Get Running VMS Only?</param>
        /// <returns>List Of VMInfo - Vm Name & Other Info.</returns>
        public List<VMInfo> GetVMList(bool runningOnly)
        {
            try
            {
                List<VMInfo> vms = new List<VMInfo>();
                VIX_FIND vmOption = VIX_FIND.REGISTERED_VMS;

                if (runningOnly)
                    vmOption = VIX_FIND.RUNNING_VMS;

                return this.VixHost.FindItems(vmOption).Select(VMInfo.CreateFromString).ToList();
            }
            catch (Exception ex)
            {
                throw new ESXPowerToolsException("Unable to reach for VM List", ex);
            }
        }

        #endregion
    }
}
